package com.springcloud.stock;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@Component
@ServerEndpoint(value = "/webSocket/{user}")
@Data
public class WebSocketHandler {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketHandler对象
     */
    private static CopyOnWriteArraySet<WebSocketHandler> webSockets = new CopyOnWriteArraySet<>();
    @Getter
    @Setter
    private Session session;

    /**
     * webSocket连接创建后调用
     */
    @OnOpen
    public void afterConnectionEstablished(Session session, @PathParam(value = "user") String user) {
        System.err.println("webSocket连接创建后调用:" + user);
        this.session = session;
        webSockets.add(this);
        System.err.println("当前连接人数："+webSockets.size());
    }

    /**
     * 接收到消息会调用
     */
    @OnMessage
    public void handleMessage(Session session, String message) throws Exception {
        System.err.println("接收前端发送的session:" + session);
        System.err.println("接收前端发送的消息内容:" + message);
        session.getBasicRemote().sendText("收到 " + session.getId() + " 的消息 ");
    }

    /**
     * 连接出错会调用
     */
    @OnError
    public void handleTransportError(Throwable exception) {
        System.err.println("接收到消息会调用");
//        sessionMap.remove(getSessionId(session));
    }

    /**
     * 连接关闭会调用
     */
    @OnClose
    public void afterConnectionClosed(Session Session) {
        System.err.println("连接关闭会调用");
        webSockets.remove(this);
    }

    /**
     * 后端发送消息
     */
    public void sendMessage(String message) {
        if (CollectionUtils.isEmpty(webSockets)){
            return;
        }
        for (WebSocketHandler socket : webSockets) {
            try {
                socket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}